<template>
	<div>
		<cl-crud @load="onLoad">
			<template #slot-filter>
				<div class="filter">
					<el-button size="mini" type="primary" @click="addChannel"
						>+添加渠道ID</el-button
					>
				</div>
				<div class="filter">
					<el-select
						placeholder="请选择阿里妈妈"
						size="mini"
						v-model="selects.taobaoId"
						@change="val => refresh({ taobaoId: val, page: 1 })"
					>
						<el-option label="全部阿里妈妈" value></el-option>
						<el-option
							v-for="(item, index) in options.union"
							:key="index"
							:label="item.account"
							:value="item.id"
						></el-option>
					</el-select>
				</div>
				<div class="filter">
					<el-select
						placeholder="请选择运营人"
						size="mini"
						v-model="selects.staffId"
						@change="val => refresh({ staffId: val, page: 1 })"
					>
						<el-option label="全部运营人" value></el-option>
						<el-option
							v-for="(item, index) in options.staff"
							:key="index"
							:label="item.username"
							:value="item.id"
						></el-option>
					</el-select>
				</div>
				<div class="filter">
					<el-select
						placeholder="请选择标签"
						size="mini"
						v-model="selects.label"
						@change="val => refresh({ label: val, page: 1 })"
					>
						<el-option label="全部标签" value></el-option>
						<el-option
							v-for="(item, index) in options.label"
							:key="index"
							:label="item"
							:value="item"
						></el-option>
					</el-select>
				</div>
				<div class="filter">
					<el-button
						@click="addStaff"
						:disabled="selectRow.length > 0 ? false : true"
						style="margin-left:10px"
						size="mini"
						type="primary"
						>绑定运营人</el-button
					>
				</div>
				<div class="filter">
					<el-button
						style="margin-left:10px"
						size="mini"
						type="primary"
						@click="addLabels"
						:disabled="selectRow.length > 0 ? false : true"
						>批量添加标签</el-button
					>
				</div>
			</template>
			<template #table-column-label="{ scope }">
				<div class="label-list">
					<el-tag
						v-for="(item, index) in scope.row.labelList"
						:key="index"
						:disable-transitions="false"
						@close="removeLabel(scope.row, index)"
						size="small"
						style="margin: 4px"
						closable
						>{{ item }}</el-tag
					>
					<a
						class="add-label"
						@click="addLabel(scope.row)"
						v-if="scope.row.labelList && scope.row.labelList.length === 0"
						>添加标签</a
					>
					<i class="el-icon-plus" @click="addLabel(scope.row)" v-else></i>
				</div>
			</template>
		</cl-crud>
		<!--创建标签弹窗-->
		<label-dig ref="label" :item="item" @refresh="refresh"></label-dig>
		<!-- 新增推广位 -->
		<cl-form ref="cl-form"></cl-form>
	</div>
</template>
<script>
import LabelDig from './components/label-dig';
export default {
	name: 'channel',
	data() {
		return {
			crud: null,
			selects: {
				taobaoId: '',
				staffId: '',
				label: ''
			},
			options: {
				union: [],
				staff: [],
				label: []
			},
			item: null,
			selectRow: [] // 当前选中行
		};
	},
	components: {
		LabelDig
	},
	created() {
		this.getFilterList();
	},
	methods: {
		onLoad({ ctx, app }) {
			this.crud = app;
			ctx.service(this.$service.account.channel)
				.set('table', {
					columns: [
						{
							type: 'selection',
							label: '全选',
							align: 'center',
							width: '60px'
						},
						{
							label: '渠道名称',
							prop: 'relationName',
							align: 'center'
						},
						{
							label: '渠道ID',
							prop: 'relationId',
							align: 'center'
						},
						{
							label: '运营人',
							prop: 'staffName',
							align: 'center'
						},
						{
							label: '标签',
							prop: 'label',
							align: 'center'
						}
					],
					props: {
						// 'default-sort': {
						// 	prop: 'relationName',
						// 	order: 'descending'
						// }
					},
					op: {
						layout: ['edit']
					},
					on: {
						'selection-change': selection => {
							this.selectRow = selection;
						}
					}
				})
				.set('upsert', {
					props: {
						title: '',
						width: '500px',
						labelWidth: '120px'
					},
					items: [
						{
							prop: 'relationId',
							label: '渠道ID：',
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写账号名称',
									clearable: true
								}
							},
							rules: [
								{
									required: true,
									message: '渠道ID不能为空'
								},
								{
									validator: (rule, value, callback) => {
										setTimeout(() => {
											if (!Number(value)) {
												callback(new Error('请输入数字值'));
											} else {
												callback();
											}
										}, 1000);
									}
								}
							]
						},
						{
							prop: 'relationName',
							label: '渠道名称：',
							component: {
								name: 'el-input',
								attrs: {
									placeholder: '请填写账号名称',
									clearable: true
								}
							},
							rules: {
								required: true,
								message: '渠道名称不能为空'
							}
						},
						{
							prop: 'taobaoId',
							label: '来源联盟：',
							component: {
								name: 'el-select',
								options: [],
								props: {
									disabled: false
								}
							},
							rules: {
								required: true,
								message: '标识不能为空'
							}
						},
						{
							prop: 'staffId',
							label: '运营人：',
							value: '',
							component: {
								name: 'el-select',
								options: []
							},
							rules: {
								required: true,
								message: '运营人不能为空'
							}
						}
					]
				})
				.set('layout', [
					['refresh-btn', 'slot-filter', 'flex1', 'search-key'],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('open', isEdit => {
					let staff = [];
					let union = [];
					if (isEdit) {
						app.setData('upsert.props.title', '编辑渠道位');
						this.upsertTitle = '编辑渠道位';
						staff.push({
							label: '无',
							value: '0'
						});
					} else {
						app.setData('upsert.props.title', '新增渠道位');
					}
					this.options.staff.forEach(item => {
						staff.push({
							label: item.username,
							value: item.id
						});
					});
					this.options.union.forEach(item => {
						union.push({
							label: item.account,
							value: item.id
						});
					});
					app.setData('upsert.items[prop:staffId].component.options', staff);
					app.setData('upsert.items[prop:taobaoId].component.options', union);
				})
				.on('refresh', async (params, { next, render }) => {
					params.size = 20;
					const { list } = await next(params);
					list.map(e => {
						e.labelList = e.label ? e.label.split(',') : [];
					});
					render(list);
				})
				.done();
			app.refresh();
		},
		refresh(params) {
			this.crud.refresh(params);
		},
		addChannel() {
			this.crud.add();
		},
		getFilterList() {
			this.getUnionList();
			this.getStaffList();
			this.getLabllist();
		},
		// 获取联盟账号
		getUnionList() {
			this.$service.account.union.list().then(res => {
				this.options.union = res;
			});
		},
		// 获取运营人列表
		getStaffList() {
			this.$service.account.extension.staffList().then(res => {
				this.options.staff = res;
			});
		},
		getLabllist() {
			this.$service.account.channel.labelList().then(res => {
				this.options.label = res;
			});
		},
		// 绑定单个运营人
		addLabel(item) {
			this.item = item;
			this.$refs.label.open(this.options.label, false);
		},
		// 批量绑定运营人
		addLabels() {
			let ids = '';
			this.selectRow.forEach(item => {
				ids = ids ? ids + ',' + item.id : item.id;
			});
			this.item = ids;
			this.$refs.label.open(this.options.label, true);
		},
		// 删除标签
		removeLabel(obj, i) {
			let labelArr = obj.labelList.filter((item, index) => {
				if (index === i) {
					return false;
				}
				return true;
			});
			this.$service.account.channel
				.update({
					id: obj.id,
					label: labelArr.join(',')
				})
				.then(() => {
					this.$message.success('删除成功');
					this.refresh();
				})
				.catch(err => {
					this.$message.error(err);
				});
		},
		addStaff() {
			let messages = '';
			let ids = '';
			this.selectRow.forEach(item => {
				ids = ids ? ids + ',' + item.id : item.id;
				if (item.staffName) {
					messages =
						messages + `<div>渠道位:${item.relationName}:已绑定${item.staffName}</div>`;
				}
			});
			if (messages) {
				this.$notify({
					title: '有选中项已有运营人',
					type: 'warning',
					dangerouslyUseHTMLString: true,
					message:
						messages +
						'<div style="color:#FF4400" >您可以不勾选已有运营人的渠道位或者将运营人编辑为无</div>'
				});
			} else {
				this.$refs['cl-form'].open({
					props: {
						label: '绑定运营人',
						labelWidth: '100px',
						width: '400px',
						showClose: false
					},
					items: [
						{
							prop: 'staffId',
							label: '运营人：',
							value: '',
							component: {
								name: 'el-select',
								options: (() => {
									let options = [];
									this.options.staff.forEach(item => {
										options.push({
											label: item.username,
											value: item.id
										});
									});
									return options;
								})()
							},
							rules: {
								required: true,
								message: '运营人不能为空'
							}
						}
					],
					on: {
						submit: ({ data, done, close }) => {
							// 提交事件
							this.$service.account.channel
								.setStaffId({
									ids,
									staffId: data.staffId
								})
								.then(res => {
									console.log(res);
									this.$message({
										message: '添加成功',
										type: 'success'
									});
									this.crud.refresh();
									done();
									close();
								})
								.catch(err => this.$message.error(err));
						}
					}
				});
			}
		}
	}
};
</script>
<style lang="stylus" scoped>
   .filter {
       margin-left 10px
   }
   .label-list {
	flexBox(center, center, row, wrap);
	.add-label {
		color $main-color
		cursor pointer
		transition .3s
		&:hover {
			opacity .8
		}
	}
	.el-icon-plus {
           color $main-color
		font-size 14px
	}
}
</style>
